package datastructure.producerconsumer;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.Semaphore;

/**
 * @Author ZhangCuirong
 * @Date 2025/7/30 13:33
 * @description:
 */
public class ProducerAndConsumer2 {
     public static Semaphore semaphore = new Semaphore(5);
    public static Queue<Integer> queue = new LinkedList<>();

    public static void main(String[] args) {
        Thread producer = new Thread(new Producer());
        Thread consumer1 = new Thread(new Consumer());
        producer.start();
        consumer1.start();
    }


    public  static  class Producer implements Runnable{

        @Override
        public void run() {
            int value = 0;
            while (true){
                try {
                    semaphore.acquire();
                    queue.add(value);
                    System.out.println("生产者生产: "+ value);
                    value++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        }
    }

    public  static  class Consumer implements Runnable{

        @Override
        public void run() {
            while (true){
                if(!queue.isEmpty()){
                    int value = queue.poll();
                    System.out.println("消费者消费: " + value);
                    semaphore.release();
                }

            }
        }
    }
}

